package com.xbjtech.realm;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.xbjtech.model.User;
import com.xbjtech.redis.RedisUtils;
import com.xbjtech.service.UserService;
import com.xbjtech.shiro.MobileYzmToken;

import tk.mybatis.mapper.entity.Example;

public class MobileYzmRealm extends AuthorizingRealm {
	
	@Autowired
	UserService userService;
	
	@Autowired
	RedisUtils redisUtils;
	
	@Autowired
	CustomRealm customRealm;
	
	/**
	 * 这里还有一个潜在问题就是MobileYzmRealm是否支持MobileYzmToken
	 */

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		return customRealm.doGetAuthorizationInfo(principals);
	}

	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		MobileYzmToken t = (MobileYzmToken) token;
		String mobile = t.getMobile();
		Example ex = new Example(User.class);
		ex.createCriteria().andEqualTo("mobile", mobile);
		List<User> list = userService.selectByExample(ex);
		if (null == list || list.size() == 0 || list.get(0) == null) {
			throw new UnknownAccountException("手机号没有匹配的帐号");
		}
		User user = list.get(0);
		
		byte[] bs = redisUtils.get(user.getMobile().getBytes());
		if (bs == null) {
			throw new IncorrectCredentialsException("验证码不正确");
		}
		String code = new String(bs);
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, code, getName());
		return info;
	}

}
